package gxprod.androidai.support;

import java.util.Vector;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;

public class ContactLookup {

	/**
	 * Gets the contact id of a person from their full or patrial name.
	 * If more than one person match the name given, the first one discovered will be returned.
	 * @return
	 */
	public static String getContactIdByName(Context context, String name) {

		Cursor cursor = context.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);
		if(cursor == null) 
			return null;

		cursor.moveToFirst();		
		while(cursor.moveToNext()) {
			String Name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)).toLowerCase();

			if(name.contains(name) | Name.contains(name)) {
				String number = cursor.getString(cursor.getColumnIndex(PhoneLookup._ID));
				cursor.close();
				return number;
			}
		}
		cursor.close();
		return null;
	}
	
	/**
	 * Gets a list of all name-contactId matches to the given name.
	 * @return
	 */
	public static Vector<StringSet> getAllContactIdsByName(Context context, String name) {
		Vector<StringSet> matches = new Vector<StringSet>();
		
		Cursor cursor = context.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);
		if(cursor == null) 
			return matches;

		cursor.moveToFirst();		
		while(cursor.moveToNext()) {
			String Name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)).toLowerCase();

			if(name.contains(name) | Name.contains(name)) {
				String number = cursor.getString(cursor.getColumnIndex(PhoneLookup._ID));
				matches.add(new StringSet(Name, number));
			}
		}
		cursor.close();		
		
		return matches;
	}
}
